<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品列表 - 商品评价系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .product-card {
            transition: all 0.3s ease;
            border: none;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            height: 100%;
        }
        .product-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }
        .product-image {
            height: 200px;
            object-fit: cover;
            border-radius: 8px 8px 0 0;
        }
        .rating {
            color: #ffc107;
        }
        .price {
            font-size: 1.25rem;
            font-weight: bold;
            color: #e74c3c;
        }
        .search-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 60px 0;
        }
        .filter-sidebar {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .category-item {
            cursor: pointer;
            padding: 8px 12px;
            border-radius: 5px;
            transition: all 0.3s;
        }
        .category-item:hover {
            background-color: #e9ecef;
        }
        .category-item.active {
            background-color: #667eea;
            color: white;
        }
        .pagination {
            justify-content: center;
        }
        .no-products {
            text-align: center;
            padding: 60px 0;
            color: #6c757d;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="/product-review/page/index">
                <i class="fas fa-shopping-cart me-2"></i>商品评价系统
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/product-review/page/index">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/product-review/page/products">商品列表</a>
                    </li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item" id="loginNav">
                        <a class="nav-link" href="/product-review/page/login">登录</a>
                    </li>
                    <li class="nav-item" id="registerNav">
                        <a class="nav-link" href="/product-review/page/register">注册</a>
                    </li>
                    <li class="nav-item dropdown" id="userNav" style="display: none;">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user me-1"></i><span id="username"></span>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="/product-review/page/user-center">个人中心</a></li>
                            <li><a class="dropdown-item" href="#" onclick="logout()">退出登录</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- 搜索区域 -->
    <section class="search-section">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-lg-8">
                    <h2 class="text-center mb-4">发现优质商品</h2>
                    <div class="input-group input-group-lg">
                        <input type="text" class="form-control" id="searchKeyword" 
                               placeholder="搜索商品名称或描述..." value="">
                        <button class="btn btn-light" type="button" onclick="searchProducts()">
                            <i class="fas fa-search"></i> 搜索
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- 主要内容 -->
    <div class="container my-5">
        <div class="row">
            <!-- 左侧筛选栏 -->
            <div class="col-lg-3">
                <div class="filter-sidebar">
                    <h5 class="mb-3"><i class="fas fa-filter me-2"></i>筛选条件</h5>
                    
                    <!-- 商品分类 -->
                    <div class="mb-4">
                        <h6 class="fw-bold mb-3">商品分类</h6>
                        <div id="categoryList">
                            <div class="category-item active" data-category="">
                                <i class="fas fa-th-large me-2"></i>全部分类
                            </div>
                        </div>
                    </div>
                    
                    <!-- 价格范围 -->
                    <div class="mb-4">
                        <h6 class="fw-bold mb-3">价格范围</h6>
                        <div class="row g-2">
                            <div class="col-6">
                                <input type="number" class="form-control form-control-sm" 
                                       id="minPrice" placeholder="最低价">
                            </div>
                            <div class="col-6">
                                <input type="number" class="form-control form-control-sm" 
                                       id="maxPrice" placeholder="最高价">
                            </div>
                        </div>
                        <button class="btn btn-sm btn-primary mt-2 w-100" onclick="filterByPrice()">
                            应用价格筛选
                        </button>
                    </div>
                    
                    <!-- 排序方式 -->
                    <div class="mb-4">
                        <h6 class="fw-bold mb-3">排序方式</h6>
                        <select class="form-select form-select-sm" id="sortBy" onchange="sortProducts()">
                            <option value="">默认排序</option>
                            <option value="price_asc">价格从低到高</option>
                            <option value="price_desc">价格从高到低</option>
                            <option value="name_asc">名称A-Z</option>
                            <option value="name_desc">名称Z-A</option>
                        </select>
                    </div>
                    
                    <!-- 重置筛选 -->
                    <button class="btn btn-outline-secondary w-100" onclick="resetFilters()">
                        <i class="fas fa-undo me-2"></i>重置筛选
                    </button>
                </div>
            </div>
            
            <!-- 右侧商品列表 -->
            <div class="col-lg-9">
                <!-- 商品数量和视图切换 -->
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <div>
                        <span class="text-muted">共找到 <span id="totalCount">0</span> 件商品</span>
                    </div>
                    <div>
                        <div class="btn-group" role="group">
                            <button type="button" class="btn btn-outline-secondary active" 
                                    onclick="switchView('grid')" id="gridViewBtn">
                                <i class="fas fa-th"></i>
                            </button>
                            <button type="button" class="btn btn-outline-secondary" 
                                    onclick="switchView('list')" id="listViewBtn">
                                <i class="fas fa-list"></i>
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- 商品网格 -->
                <div id="productGrid" class="row">
                    <!-- 商品卡片将通过JavaScript动态加载 -->
                </div>
                
                <!-- 无商品提示 -->
                <div id="noProducts" class="no-products" style="display: none;">
                    <i class="fas fa-box-open fa-4x mb-3"></i>
                    <h4>暂无商品</h4>
                    <p>没有找到符合条件的商品，请尝试调整筛选条件</p>
                </div>
                
                <!-- 分页 -->
                <nav aria-label="商品分页" class="mt-5">
                    <ul class="pagination" id="pagination">
                        <!-- 分页按钮将通过JavaScript动态生成 -->
                    </ul>
                </nav>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer class="bg-dark text-light py-4 mt-5">
        <div class="container">
            <div class="text-center">
                <p>&copy; 2024 商品评价系统. All rights reserved.</p>
            </div>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // 全局变量
        let currentPage = 1;
        let pageSize = 12;
        let currentCategory = '';
        let currentKeyword = '';
        let currentSort = '';
        let currentView = 'grid';
        
        $(document).ready(function() {
            // 检查登录状态
            checkLoginStatus();
            
            // 加载商品分类
            loadCategories();
            
            // 加载商品列表
            loadProducts();
            
            // 搜索框回车事件
            $('#searchKeyword').keypress(function(e) {
                if (e.which === 13) {
                    searchProducts();
                }
            });
        });
        
        // 检查登录状态
        function checkLoginStatus() {
            $.ajax({
                url: '/product-review/user/current',
                type: 'GET',
                success: function(result) {
                    if (result.code === 200 && result.data) {
                        $('#loginNav, #registerNav').hide();
                        $('#userNav').show();
                        $('#username').text(result.data.username);
                    } else {
                        $('#loginNav, #registerNav').show();
                        $('#userNav').hide();
                    }
                },
                error: function() {
                    $('#loginNav, #registerNav').show();
                    $('#userNav').hide();
                }
            });
        }
        
        // 加载商品分类
        function loadCategories() {
            $.ajax({
                url: '/product-review/product/categories',
                type: 'GET',
                success: function(result) {
                    if (result.code === 200 && result.data) {
                        let html = '<div class="category-item active" data-category=""><i class="fas fa-th-large me-2"></i>全部分类</div>';
                        result.data.forEach(function(category) {
                            html += `<div class="category-item" data-category="\${category}"><i class="fas fa-tag me-2"></i>\${category}</div>`;
                        });
                        $('#categoryList').html(html);
                        
                        // 绑定分类点击事件
                        $('.category-item').click(function() {
                            $('.category-item').removeClass('active');
                            $(this).addClass('active');
                            currentCategory = $(this).data('category');
                            currentPage = 1;
                            loadProducts();
                        });
                    }
                }
            });
        }
        
        // 加载商品列表
        function loadProducts() {
            const params = {
                page: currentPage,
                size: pageSize
            };
            
            if (currentCategory) {
                params.category = currentCategory;
            }
            
            if (currentKeyword) {
                params.keyword = currentKeyword;
            }
            
            if (currentSort) {
                params.sort = currentSort;
            }
            
            $.ajax({
                url: '/product-review/product/page',
                type: 'GET',
                data: params,
                success: function (result) {
                    if (result.code === 200 && result.data) {
                        const products = result.data.list || [];
                        const total = result.data.total || 0;

                        displayProducts(products);
                        updatePagination(total);
                        $('#totalCount').text(total);
                    } else {
                        displayProducts([]);
                        updatePagination(0);
                        $('#totalCount').text(0);
                    }
                },

                error: function() {
                    displayProducts([]);
                    updatePagination(0);
                    $('#totalCount').text(0);
                }
            });
        }
        
        // 显示商品列表
        function displayProducts(products) {
            if (products.length === 0) {
                $('#productGrid').hide();
                $('#noProducts').show();
                return;
            }
            
            $('#noProducts').hide();
            $('#productGrid').show();
            
            let html = '';
            products.forEach(function(product) {
                if (currentView === 'grid') {
                    html += createProductCard(product);
                } else {
                    html += createProductListItem(product);
                }
            });
            
            $('#productGrid').html(html);
        }
        
        // 创建商品卡片
        function createProductCard(product) {
            return `
                <div class="col-lg-4 col-md-6 mb-4">
                    <div class="card product-card">
                        <img src="\${product.imageUrl || '/product-review/static/img/default-product.jpg'}" 
                             class="card-img-top product-image" alt="\${product.name}">
                        <div class="card-body d-flex flex-column">
                            <h5 class="card-title">\${product.name}</h5>
                            <p class="card-text text-muted flex-grow-1">\${product.description || '暂无描述'}</p>
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span class="price">¥\${product.price}</span>
                                <div class="rating">
                                    <i class="fas fa-star"></i>
                                    <i class="fas fa-star"></i>
                                    <i class="fas fa-star"></i>
                                    <i class="fas fa-star"></i>
                                    <i class="fas fa-star"></i>
                                    <small class="text-muted ms-1">(0)</small>
                                </div>
                            </div>
                            <div class="d-flex gap-2">
                                <a href="/product-review/page/product-detail?id=\${product.id}" 
                                   class="btn btn-primary flex-grow-1">查看详情</a>
                                <button class="btn btn-outline-primary" onclick="addToFavorites(\${product.id})">
                                    <i class="fas fa-heart"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }
        
        // 创建商品列表项
        function createProductListItem(product) {
            return `
                <div class="col-12 mb-3">
                    <div class="card product-card">
                        <div class="row g-0">
                            <div class="col-md-3">
                                <img src="\${product.imageUrl || '/product-review/static/img/default-product.jpg'}" 
                                     class="img-fluid h-100" alt="\${product.name}" style="object-fit: cover;">
                            </div>
                            <div class="col-md-9">
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-8">
                                            <h5 class="card-title">\${product.name}</h5>
                                            <p class="card-text">\${product.description || '暂无描述'}</p>
                                            <div class="rating mb-2">
                                                <i class="fas fa-star"></i>
                                                <i class="fas fa-star"></i>
                                                <i class="fas fa-star"></i>
                                                <i class="fas fa-star"></i>
                                                <i class="fas fa-star"></i>
                                                <small class="text-muted ms-1">(0条评价)</small>
                                            </div>
                                        </div>
                                        <div class="col-md-4 text-end">
                                            <div class="price mb-3">¥\${product.price}</div>
                                            <div class="d-flex flex-column gap-2">
                                                <a href="/product-review/page/product-detail?id=\${product.id}" 
                                                   class="btn btn-primary">查看详情</a>
                                                <button class="btn btn-outline-primary" onclick="addToFavorites(\${product.id})">
                                                    <i class="fas fa-heart me-1"></i>收藏
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }
        
        // 更新分页
        function updatePagination(total) {
            const totalPages = Math.ceil(total / pageSize);
            let html = '';
            
            if (totalPages <= 1) {
                $('#pagination').html('');
                return;
            }
            
            // 上一页
            if (currentPage > 1) {
                html += `<li class="page-item"><a class="page-link" href="#" onclick="goToPage(${currentPage - 1})">上一页</a></li>`;
            }
            
            // 页码
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, currentPage + 2);
            
            for (let i = startPage; i <= endPage; i++) {
                const activeClass = i === currentPage ? 'active' : '';
                html += `<li class="page-item ${activeClass}"><a class="page-link" href="#" onclick="goToPage(${i})">${i}</a></li>`;
            }
            
            // 下一页
            if (currentPage < totalPages) {
                html += `<li class="page-item"><a class="page-link" href="#" onclick="goToPage(${currentPage + 1})">下一页</a></li>`;
            }
            
            $('#pagination').html(html);
        }
        
        // 跳转到指定页面
        function goToPage(page) {
            currentPage = page;
            loadProducts();
            $('html, body').animate({scrollTop: 0}, 500);
        }
        
        // 搜索商品
        function searchProducts() {
            currentKeyword = $('#searchKeyword').val().trim();
            currentPage = 1;
            loadProducts();
        }
        
        // 按价格筛选
        function filterByPrice() {
            const minPrice = $('#minPrice').val();
            const maxPrice = $('#maxPrice').val();
            
            // 这里可以添加价格筛选逻辑
            // 由于后端接口可能不支持价格范围筛选，这里只是示例
            alert('价格筛选功能待完善');
        }
        
        // 排序商品
        function sortProducts() {
            currentSort = $('#sortBy').val();
            currentPage = 1;
            loadProducts();
        }
        
        // 重置筛选
        function resetFilters() {
            currentCategory = '';
            currentKeyword = '';
            currentSort = '';
            currentPage = 1;
            
            $('#searchKeyword').val('');
            $('#minPrice').val('');
            $('#maxPrice').val('');
            $('#sortBy').val('');
            
            $('.category-item').removeClass('active');
            $('.category-item[data-category=""]').addClass('active');
            
            loadProducts();
        }
        
        // 切换视图
        function switchView(view) {
            currentView = view;
            
            if (view === 'grid') {
                $('#gridViewBtn').addClass('active');
                $('#listViewBtn').removeClass('active');
            } else {
                $('#listViewBtn').addClass('active');
                $('#gridViewBtn').removeClass('active');
            }
            
            loadProducts();
        }
        
        // 添加到收藏
        function addToFavorites(productId) {
            // 检查登录状态
            $.ajax({
                url: '/product-review/user/current',
                type: 'GET',
                success: function(result) {
                    if (result.code === 200 && result.data) {
                        // 已登录，添加收藏逻辑
                        alert('收藏功能待完善');
                    } else {
                        // 未登录，跳转到登录页
                        if (confirm('请先登录后再收藏商品，是否前往登录？')) {
                            window.location.href = '/product-review/page/login';
                        }
                    }
                }
            });
        }
        
        // 退出登录
        function logout() {
            $.ajax({
                url: '/product-review/user/logout',
                type: 'POST',
                success: function(result) {
                    if (result.code === 200) {
                        location.reload();
                    } else {
                        alert('退出登录失败：' + result.message);
                    }
                },
                error: function() {
                    alert('退出登录失败');
                }
            });
        }
    </script>
</body>
</html>